<?php

class Phongban extends Model
{
    public function selectAll()
    {
        $sql = <<<SQL
SELECT pb.dv_id AS pb_id, dv_ten as pb_ten
FROM phongban pb NATURAL JOIN donvi
SQL;
        return $this->_db->run($sql);
    }

    public function getTen($id)
    {
        $sql = <<<SQL
SELECT dv_ten FROM donvi NATURAL JOIN phongban WHERE donvi.dv_id = :id
SQL;
        $data = $this->_db->run($sql, array('id' => $id));
        return $data[0]['dv_ten'];
    }

    public function update_ten($id, $ten)
    {
        $donvi = new Donvi();
        $donvi->update(array('dv_ten' => $ten), 'dv_id = :id', array('id' => $id));
    }

    public function delPhongBan($id)
    {
        # Xóa các cán bộ thuộc phòng ban này

        $this->_db->run('DELETE FROM cbhanhchinh WHERE dv_id = :id', array('id' => $id));
        $this->delete('dv_id = :id', array('id' => $id));

    }

    public function addPhongBan($ten)
    {
        $this->_db->run('INSERT INTO donvi (dv_ten) values (:ten)', array('ten' => $ten));
        $newId = $this->_db->lastInsertId();
        $this->_db->run('INSERT INTO phongban(dv_id) VALUES(:id)', array('id' => $newId));

        return $newId;
    }
}
